package com.niiwoo.civet.trade.service.local.loan;

import com.niiwoo.civet.trade.dao.entity.ReturnProjectRecord;
import com.niiwoo.civet.trade.dao.mapper.ReturnProjectRecordMapperExt;
import com.niiwoo.civet.trade.enums.ProjectTypeEnum;
import com.niiwoo.civet.trade.enums.ReturnProjectProcessSchemeEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author wping
 * @Description: 贷前退回标的记录服务类
 * @date 2018/5/2 10:40
 */
@Slf4j
@Service
public class ReturnProjectRecordService {

    @Autowired
    private ReturnProjectRecordMapperExt returnProjectRecordMapperExt;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 插入贷前退回标的记录表
     *
     * @param projectId         标的ID
     * @param projectTypeEnum   标的类型
     * @param userId            用户ID
     * @param returnReason      退回原因
     * @param remark            备注
     * @param processSchemeEnum 操作方案
     * @return 成功返回true, 否则false
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean insertReturnProjectRecord(Long projectId, ProjectTypeEnum projectTypeEnum, String userId, String returnReason, String remark, ReturnProjectProcessSchemeEnum processSchemeEnum) {

        String methodName = "插入贷前退回标的记录表, projectId:" + projectId + ", userId:" + userId + ", returnReason:" + returnReason;
        if (projectId == null || projectTypeEnum == null || StringUtils.isEmpty(userId) || processSchemeEnum == null) {
            log.error(methodName + "-失败, projectId/projectTypeEnum/userId/processSchemeEnum为空");
            return false;
        }

        Date now = new Date();
        ReturnProjectRecord returnProjectRecord = new ReturnProjectRecord();
        returnProjectRecord.setId(snowflakeIdWorker.nextId());
        returnProjectRecord.setProjectId(projectId);
        returnProjectRecord.setProjectType(projectTypeEnum.getValue());
        returnProjectRecord.setUserId(userId);
        returnProjectRecord.setReturnReason(returnReason);
        returnProjectRecord.setRemark(remark);
        returnProjectRecord.setProcessScheme(processSchemeEnum.getProcessScheme());
        returnProjectRecord.setCreateTime(now);
        returnProjectRecord.setUpdateTime(now);

        int count = returnProjectRecordMapperExt.insertSelective(returnProjectRecord);

        log.info(methodName + "-插入条数:{}", count);

        return true;
    }

    /**
     * 通过标的id查询最近一条退回记录
     *
     * @param projectId 标的ID
     * @return
     */
    public ReturnProjectRecord selectLatelyRecordByUserIdProjectId(String userId, Long projectId) {
        return returnProjectRecordMapperExt.selectLatelyRecordByProjectId(userId, projectId);
    }

}
